/* Copyright  2009-2010
   @Author
   Richard Changde Yin            e-mail yinchangde@hotmail.com

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/**
 * @filename: mutex.h
 */
#ifndef __MUTEX_H__
#define __MUTEX_H__


#include<os.h>

typedef int Lock;
class Mutex
{

#if defined(sparc) || defined(i686) || defined(x86_64)
    Lock lock;
#else
    pthread_mutex_t mutex_;
#endif
public:
    char name[20];
    Mutex();
    virtual ~Mutex();
    int init();
    int init     (char *name);
    int tryLock  (int tries=0,  int  waitmsecs=0);
    int getLock  (int procSlot, bool procAccount=true);
    int releaseLock(int procSlot, bool procAccount=true);
    int destroy();
    int recoverMutex();

};


class SimpleMutex {

protected:
    pthread_mutex_t* ref_mutex ;
    SimpleMutex();
    SimpleMutex& operator = (SimpleMutex&);
    SimpleMutex(SimpleMutex&);
    SimpleMutex(const SimpleMutex&);
public:

    SimpleMutex(pthread_mutex_t& in_mutex){
        ref_mutex  = &in_mutex ;
        pthread_mutex_lock(ref_mutex) ;
    }
    SimpleMutex(pthread_mutex_t* in_mutex){
        ref_mutex  = in_mutex ;
        pthread_mutex_lock(ref_mutex) ;
    }
    virtual ~SimpleMutex() {
        pthread_mutex_unlock(ref_mutex) ;
    }
};
#endif /*__MUTEX_H__*/
